package externalflame.systemdesign.newsfeed.service.impl;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import externalflame.systemdesign.newsfeed.dao.UserDao;
import externalflame.systemdesign.newsfeed.entity.User;
import externalflame.systemdesign.newsfeed.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.PermissionDeniedDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class SimpleUserService implements UserService {

    @Autowired
    UserDao userDao;

    IdentifierGenerator identifierGenerator = new DefaultIdentifierGenerator();

    @Transactional(isolation = Isolation.SERIALIZABLE)
    @Override
    public User login(String userName, String password) {
        User user = userDao.getByUserName(userName);
        if (user == null) {
            userDao.insert(identifierGenerator.nextId(User.class).longValue(), userName, password, new Date().getTime());
            user = userDao.getByUserName(userName);
        } else {
            if (!user.getPassword().equals(password)) {
                throw new PermissionDeniedDataAccessException("password incorrect", null);
            }
        }
        return user;
    }
}
